// 管理用户数据相关
import { ref } from 'vue'
import { defineStore } from 'pinia'
import { loginAPI } from '@/apis/user'
import { useCartStore } from './cartStore'
import { memberMergeAPI } from '@/apis/cart'
export const useUserStore = defineStore('user', () => {
    // 定义管理用户数据得state
    const userInfo = ref({})
    // 定义获取接口数据得action函数
    const getUserInfo = async ({ account, password }) => {
        const res = await loginAPI({ account, password })
        userInfo.value = res.result
        console.log('userinfo', userInfo.value);
        // 登录时将购物车数据同步到数据库
        const cartStore = useCartStore()
        await memberMergeAPI(cartStore.cartList.map(item => {
            return {
                skuId: item.skuId,
                selected: item.selected,
                count: item.count
            }
        }))
        cartStore.updateCartList()
    }


    // 推出时清除用户信息
    const clearUserInfo = () => {
        userInfo.value = {}
        // 清除购物车
        const cartStore = useCartStore()
        cartStore.clearCart()
    }
    // 以对象得格式将state和action return出去
    return { userInfo, getUserInfo, clearUserInfo }
    // 运用插件进行数据得持久化存储


},
    {
        persist: true
    }
)